/*
 * @Author: Jiraiya
 * @Date: 2020-05-06 14:31:03
 * @LastEditors: Jiraiya
 * @LastEditTime: 2020-05-07 15:34:08
 * @Description: 
 */
const fg = require('fast-glob')
const _ = require('lodash')
const path2reg = require('path-to-regexp')

module.exports = {
    /**
     * 查找某个目录下，满足某种GLOB模式的文件，返回所有文件列表
     * @param baseDir {string} 基础目录
     * @param pattern {Array|string} 模式数组
     * @param options {object?} 传给 fast-glob 的配置
     * @returns {Array} 匹配的文件路径列表
     */
    findFiles(baseDir, pattern, options){
        let out = [];
        
        if(typeof pattern === 'string'){
            pattern = [ `${baseDir}${pattern}` ];
        }else{
            pattern = pattern.map( (obj) => {
                return `${baseDir}${obj}`;
            });
        }

        out = fg.sync(pattern, options);

        return out;
    },

    /**
     * 自定义的配置合并过程，如果值是数组，则直接覆盖
     * @param objValue
     * @param srcValue
     * @returns {*}
     */
    mergeHandle(objValue, srcValue){
        if (_.isArray(srcValue)) {
            return srcValue;
        }
    },
    
    /**
     * 加载配置文件数组中的文件，merge成一个配置，数组中靠后的同名配置项会覆盖前面的
     * @param confArray {Array} 要加载的文件列表
     * @returns {{}}
     */
    mergeConfigFiles(confArray){
        let out = {};

        confArray.forEach( (file) => {
            let conf = require(file);
            _.mergeWith(out, conf, this.mergeHandle);
        });

        return out;
    },

    /**
     * @description: 获取真实路径和参数
     * @param {type} 
     * @return: 
     */  
    matchRouter(path = '/', rules = []){

        const out = {
            real: path,
            params: {},
        }
        
        const {match, pathToRegexp} = path2reg;
        const realObj = rules.find(item => {
            return pathToRegexp(item.match).exec(path);
        })
    
        if(realObj){
            const { params } = match(realObj.match, { decode: decodeURIComponent })(path);
            out.params = params || {};
            out.real = realObj.rewrite;
        }
        return out;
    },

    /**
     * @description: 检测是否是API路径
     * @param {type} 
     * @return: 
     */    
    isApi(path, apiRoot){
        return path.startsWith(apiRoot);
    },

    /**
     * @description: 获取环境
     * @param {type} 
     * @return: 
     */    
    getNodeEnv(){
        return process.env.NODE_ENV || 'production';
    }
}